using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text.Json;
using System.Net.Http.Json;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components;
using AntDesign;
using ImoviesBlazorAntPro.Shared.Dtos;
using ImoviesBlazorAntPro.Shared.Utils;

namespace ImoviesBlazorAntPro.Client.Pages
{
    public partial class Teleplay
    {
        [Inject]
        public HttpClient HttpClient { get; set; }
        [Inject]
        public IJSRuntime Js { get; set; }
        [Inject]
        public IMessageService MessageService { get; set; }


        // 所有年份数据
        public List<uint> totalYears = new List<uint>();
        // 视频列表数据
        public List<TeleplayDataList> teleplayDataList = new List<TeleplayDataList>();
        // 年度点评数据
        public List<AnnualReviewDto> annualReviews = new List<AnnualReviewDto>();

        // 视频播放链接缓存
        public Dictionary<string, List<TeleplayVlinkDto>> vlinkCache = new Dictionary<string, List<TeleplayVlinkDto>>();

        // 页大小
        public int pageSize = 12;
        // 当前页
        public int currentPage = 1;
        // 总数据条数
        public int tatalCount;
        // 播放器是否显示
        public bool playerIsVisible = false;
        // 真实播放地址
        public string realPlayUrl = string.Empty;
        // 当前视频名称
        public string currentVideo = string.Empty;
        // 播放器标题
        public string playerTitle = string.Empty;
        // 暂存前一次展开链接列表的视频id
        public string oldVideoId = string.Empty;
        // 暂存前一次需解析视频地址
        public string oldOriginPlayUrl = string.Empty;


        /// <summary>
        /// 顶部年份导航标签随机颜色
        /// </summary>
        /// <returns></returns>
        public string GetTagColor()
        {
            string[] colors = { "#f50", "#2db7f5", "#87d068", "#108ee9", "#693aec", "#8fc992", "#ff69b4" };
            return colors[new Random().Next(colors.Length - 1)];
        }

        /// <summary>
        /// 调用js进行锚点跳转
        /// </summary>
        /// <param name="anchorName"></param>
        /// <returns></returns>
        public async Task GoAnchor(string anchorName)
        {
            await Js.InvokeVoidAsync("goAnchor", anchorName);
        }

        /// <summary>
        /// 年度评论语
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        public string GetAnnualReview(uint year)
        {
            return annualReviews.FirstOrDefault(x => x.Year == year)?.Comment ?? "暂无评语";
        }


        /// <summary>
        /// 通过id获取视频链接列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task GetVlinksById(string id)
        {
            if (vlinkCache.ContainsKey(id))
            {
                return;
            }
            // 获取视频播放链接
            var resp = await HttpClient.GetAsync($"/api/teleplay/vlist/{id}");
            var list = JsonSerializer.Deserialize<List<TeleplayVlinkDto>>(await resp.Content.ReadAsStringAsync(),
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                IncludeFields = true,
            });
            if (list != null || list.Count > 0)
            {
                vlinkCache.Add(id, list);
            }
        }


        /// <summary>
        /// 获取真实播放地址
        /// </summary>
        /// <param name="url">原url</param>
        public async Task GetRealPlayLink(string name, string url)
        {
            // 真实播放地址为空或需解析地址不等于上次地址时才进行请求
            if (string.IsNullOrEmpty(realPlayUrl) || url != oldOriginPlayUrl)
            {
                // 真实地址解析
                var resp = await HttpClient.PostAsJsonAsync<LinkParseReqParameter>("/api/playlink", new LinkParseReqParameter { Vcate = "Teleplay", OriginUrl = url });
                realPlayUrl = await resp.Content.ReadAsStringAsync();
                oldOriginPlayUrl = url;
                if (string.IsNullOrEmpty(realPlayUrl))
                {
                    MessageService.Warning("解析失败！");
                    return;
                }
            }
            playerTitle = $"正在播放 「{currentVideo}-{name}」";
            playerIsVisible = true;
        }


        /// <summary>
        /// 播放器关闭
        /// </summary>
        public void PlayerClose()
        {
            //realPlayUrl = string.Empty;
            playerTitle = string.Empty;
            playerIsVisible = false;
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="args"></param>
        public async Task OnPaginationChangeAsync(PaginationEventArgs args)
        {
            currentPage = args.Page;
            var resp = await HttpClient.GetAsync($"/api/teleplay?pageSize={pageSize}&pageNum={currentPage}");
            var resData = JsonSerializer.Deserialize<PaginationList<TeleplayDataList>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            teleplayDataList.Concat(resData.Data);
            tatalCount = resData.Total;
        }


        /// <summary>
        /// 生命周期，加载完毕
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            // 获取所有年份
            totalYears = await HttpClient.GetFromJsonAsync<List<uint>>("/api/teleplay/years");
            // 获取视频列表
            var resp = await HttpClient.GetAsync($"/api/teleplay?pageSize={pageSize}&pageNum={currentPage}");
            var resData = JsonSerializer.Deserialize<PaginationList<TeleplayDataList>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            teleplayDataList = resData.Data;
            tatalCount = resData.Total;

            // 获取年度点评
            var resp2 = await HttpClient.GetAsync($"/api/AnnualReview/{(uint)AnnualReviewsVideoCate.Teleplay}");
            annualReviews = JsonSerializer.Deserialize<List<AnnualReviewDto>>(await resp2.Content.ReadAsStringAsync(),
               new JsonSerializerOptions
               {
                   PropertyNameCaseInsensitive = true,
                   IncludeFields = true,
               });
            await base.OnInitializedAsync();
        }
    }
}